import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;

public class MemoryManager {// stores Page File, Physical Memory, And TLB
	
int[]PageFile = new int[256];
int[][]PhysicalMemory = new int[256][256];
int[]TLB = new int[16];
int PhysicalMemorysize = 0;

public MemoryManager(){ 
	initalisePageFile();
}

public void initalisePageFile(){ //index sores the page Number, frame number stored in array, -1 if it hasnt been found yet
	for(int i=0;i<PageFile.length;i++){
		PageFile[i] = -1;
	}
}
public int Search(int PageNumber){
	if(PageFile[PageNumber] == -1){
		//System.out.println("not found in page file, adding from backing store");  // increment paging counter 
			int frameNumber =  AddtoPageFile(PageNumber);
			PageFile[PageNumber] = frameNumber;
		}
	else {
		//	System.out.println("found in pagefile returning frameNumber");
		}		
	return PageFile[PageNumber];
}
private int AddtoPageFile(int pagenumber) {
	int pageNumber = pagenumber;
	int BackingStoreStart = pageNumber * 256; 
	int frameNumber = -1;

	frameNumber =PhysicalMemorysize;
	File fileName;
 	RandomAccessFile disk = null;
	try {
           fileName = new File("BACKING_STORE");
           disk = new RandomAccessFile(fileName, "rw");
		/**
		 * read() returns a byte, but since bytes
		 * in Java are signed, we use an integer
		 * to store its value to obtain the signed
		 * value of the byte.
		 */
					
		// seek to byte position Backing store start
		disk.seek(BackingStoreStart);

		// now read 4 bytes
		byte[] data = new byte[256];
		disk.read(data);
		for (int i = 0; i < 256; i++) {
		PhysicalMemory[frameNumber][i] = data[i];
	     }
	PhysicalMemorysize++;
	disk.close();
	}
	catch (IOException e) {
           System.err.println ("Unable to start the disk");
           System.exit(1);
      }
	return frameNumber;
}

public ArrayList calculateFrameNumber(ArrayList<ArrayList<Integer>> testArray) {
	for(int i = 0;i < testArray.size();i++){
		int PageNumber = testArray.get(i).get(2);
		int frameNumber =Search(PageNumber);
		testArray.get(i).add(frameNumber);	
	}
	return testArray;
}

public ArrayList getFromPhysicalMemory(ArrayList<ArrayList<Integer>> testArray) {
	for(int i = 0;i<testArray.size();i++){
		int value = 0;
		int frameNumber = testArray.get(i).get(4);
		int Offset = testArray.get(i).get(3);
		value = PhysicalMemory[frameNumber][Offset];
		testArray.get(i).add(value);
	}
return testArray;
}


}